package com.jw.debezuim.config.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Order(1)
@Component
public class CommonFilter extends OncePerRequestFilter {
    private static Logger logger = LoggerFactory.getLogger(CommonFilter.class);
    public static final String REQUESTID = "requestId";

    @Override
    public void initFilterBean() {
        logger.info("CommonFilter init");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            try {
                String requestId = UUID.randomUUID().toString();
                MDC.put(REQUESTID, requestId);//日志格式添加请求链
            } catch (IllegalArgumentException e) {
                logger.error("过滤器异常捕获", e);
            }
            filterChain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }

    @Override
    public void destroy() {

    }
}